package com.javandad.app.server.servlet;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.javandad.app.client.home.HomeService;
import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.shared.entity.home.HomePost;

@SuppressWarnings("serial")
public class HomeServlet extends RemoteServiceServlet implements HomeService {

	private final static int PAGE_SIZE = 20;

	DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();

	@Override
	public List<HomePost> downloadPosts(String username, int count) {
		PersistenceManager pm = PMFSingleton.getPM();
		DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();
		// HttpSession session = this.getThreadLocalRequest().getSession();

		List<HomePost> hp = dbm.getHomePosts(username, null, pm);

		return hp.subList(0, hp.size() < (count * PAGE_SIZE) ? hp.size() : (count * PAGE_SIZE));
	}

	@Override
	public List<String> getSessionInfo() {
		List<String> list = new LinkedList<String>();
		HttpSession session = this.getThreadLocalRequest().getSession();
		list.add((String) session.getAttribute("mode"));
		list.add((String) session.getAttribute("username"));

		return list;
	}

	@Override
	public HomePost uploadPost(HomePost post) {

		try {
			PersistenceManager pm = PMFSingleton.getPM();
			HttpSession session = this.getThreadLocalRequest().getSession();

			String poster = (String) session.getAttribute("username");
			if (poster == null || poster.equals("")) {
				poster = "Anonymous";
			}

			post.setPoster(poster);
			post.setDateOfPost(new Date());

			pm.makePersistent(post);
			pm.close();
			return post;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
